/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PesquisaPessoaView.java
 *
 * Created on 23/05/2011, 14:04:39
 */

package br.com.comprasPublicas.view.pesquisa;

import br.com.comprasPublicas.entity.Pessoa;
import br.com.comprasPublicas.util.HibernateUtil;
import br.com.comprasPublicas.view.cadastro.CotacaoView;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author helsen
 */
public class PesquisaPessoaView extends javax.swing.JDialog {

    /** Creates new form PesquisaPessoaView */
    public PesquisaPessoaView(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        preencher_tblFornecedores();
        tblFornecedores.setSelectionMode(0);

        //Método utilizado para centralizar o JFrame na tela
        Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((tela.width - this.getSize().width) / 2, (tela.height - this.getSize().height) / 2);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblFornecedores = new javax.swing.JTable();
        btnSelecionar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtFornecedor = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnConsultar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblFornecedores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Cod.", "Fornecedor"
            }
        ));
        tblFornecedores.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tblFornecedores.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tblFornecedores.setName("tblFornecedores"); // NOI18N
        tblFornecedores.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        tblFornecedores.getTableHeader().setResizingAllowed(false);
        tblFornecedores.getTableHeader().setReorderingAllowed(false);
        tblFornecedores.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tblFornecedoresFocusLost(evt);
            }
        });
        jScrollPane1.setViewportView(tblFornecedores);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(br.com.comprasPublicas.compraspublicas.ComprasPublicasApp.class).getContext().getResourceMap(PesquisaPessoaView.class);
        btnSelecionar.setFont(resourceMap.getFont("btnSelecionar.font")); // NOI18N
        btnSelecionar.setMnemonic('s');
        btnSelecionar.setText(resourceMap.getString("btnSelecionar.text")); // NOI18N
        btnSelecionar.setName("btnSelecionar"); // NOI18N
        btnSelecionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setName("jPanel1"); // NOI18N

        txtFornecedor.setName("txtFornecedor"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        btnConsultar.setFont(resourceMap.getFont("btnConsultar.font")); // NOI18N
        btnConsultar.setMnemonic('c');
        btnConsultar.setText(resourceMap.getString("btnConsultar.text")); // NOI18N
        btnConsultar.setName("btnConsultar"); // NOI18N
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtFornecedor, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(279, Short.MAX_VALUE)
                .addComponent(btnConsultar)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnConsultar))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnSelecionar))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnSelecionar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblFornecedoresFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tblFornecedoresFocusLost

}//GEN-LAST:event_tblFornecedoresFocusLost

    private void btnSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarActionPerformed
        if (tblFornecedores.getSelectedRow()==-1){
         JOptionPane.showMessageDialog(null, "Nenhum Fornecedor Selecionado");
        }
        else{
            String selecao = tblFornecedores.getModel().getValueAt(tblFornecedores.getSelectedRow(), 0).toString();
            CotacaoView.pess = selecao;
            fornecedores = null;
            dispose();
        }
}//GEN-LAST:event_btnSelecionarActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        lista_fornecedor();
}//GEN-LAST:event_btnConsultarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PesquisaPessoaView dialog = new PesquisaPessoaView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnSelecionar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblFornecedores;
    private javax.swing.JTextField txtFornecedor;
    // End of variables declaration//GEN-END:variables
public void preencher_tblFornecedores()
    {
        try
        {
            tblFornecedores.getColumnModel().getColumn(0).setPreferredWidth(50);
            tblFornecedores.getColumnModel().getColumn(1).setPreferredWidth(500);

            DefaultTableModel modelo_tbl = (DefaultTableModel) tblFornecedores.getModel();
            modelo_tbl.setNumRows(0);

            btnConsultarActionPerformed(null);

        }
        catch(Exception erro)
        {
            JOptionPane.showMessageDialog(null, "Não foi possível preencher tabela "+erro);
        }
    }

    private List lista_fornecedor(){
        Session sessao = HibernateUtil.getSessao();
        Transaction transacao = sessao.beginTransaction();

        //Utilizando criteria para instanciar Produto.class
        Criteria crit = sessao.createCriteria(Pessoa.class);
        String fornBusca = txtFornecedor.getText();

        //Buscando conforme restrição
        crit.add(Restrictions.ilike("nome_razao_soc", fornBusca, MatchMode.ANYWHERE));//Anywhere: irá buscar por %fornBusca%
        List lista = crit.list();

        DefaultTableModel modelo_tbl = (DefaultTableModel) tblFornecedores.getModel();
        modelo_tbl.setNumRows(0);

        pessoa = new Pessoa();

        int tamanho_lista = lista.size();
        for (int i=0; i<tamanho_lista; i++)
        {
            pessoa = (Pessoa) lista.get(i);
            modelo_tbl.addRow(new Object[]{pessoa.getId_pessoa(),
                                            pessoa.getNome_razao_soc(),
                                            });
        }
        transacao.commit();
        sessao.close();

        return pessoaList;
    }


    private List<Pessoa> fornecedores;
    private Pessoa pessoa;
    private List pessoaList;
}
